package com.gitee.deament.tianyancha.core.aop;

import com.alibaba.fastjson.JSONObject;
import com.gitee.deament.tianyancha.core.TianyanchaResult;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 切面管理请求
 *
 * @author Deament
 */
@Aspect
public class TianyanchaCacheAop implements Ordered {
    /**
     * 可以缓存redis 等等
     */
    private ConcurrentHashMap<String, TianyanchaResult> cache = new ConcurrentHashMap<>();
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Before("execution(* com.gitee.deament.tianyancha.core.base.BaseRequest.get(..))")
    public void before() {
        logger.debug("前置");
    }

    @After("execution(* com.gitee.deament.tianyancha.core.base.BaseRequest.get(..))")
    public void after() {
        logger.debug("通知方法返回或者异常后调用");
    }

    @AfterReturning("execution(* com.gitee.deament.tianyancha.core.base.BaseRequest.get(..))")
    public void afterReturning() {
        logger.debug("通知方法完成后调用");
    }

    @AfterThrowing("execution(* com.gitee.deament.tianyancha.core.base.BaseRequest.get(..))")
    public void afterThrowing() {
        logger.debug("通知方法异常后调用");
    }

    @Around("execution(* com.gitee.deament.tianyancha.core.base.BaseRequest.get(..))")
    public TianyanchaResult around(ProceedingJoinPoint pj) {
        try {
            Object[] args = pj.getArgs();
            //args 实际上 只有一个DTO
            Object objects = args[0];
            String cacheKey = objects.getClass().getName() + ":" + JSONObject.toJSONString(objects);
            //logger.info("cacheKey=" + cacheKey);
            TianyanchaResult cacheResult = cache.get(cacheKey);
            if (cacheResult != null) {
                //   logger.info("返回缓存里的值");
                return cacheResult;
            }
            cacheResult = (TianyanchaResult) pj.proceed();
            if (cacheResult.isSuccess()) {
                cache.put(cacheKey, cacheResult);
            }
            return cacheResult;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        // logger.info("环绕结束");
        return new TianyanchaResult();
    }

    @Override
    public int getOrder() {
        return 2;
    }
}
